<script>
  import FormField from "$lib/components/common/FormField.svelte";
  import NumberField from "$lib/components/common/NumberField.svelte";
  import SwitchField from "$lib/components/common/SwitchField.svelte";
  import MultipleField from "$lib/components/common/MultipleField.svelte";
  import DepartmentSelect from "$lib/components/common/DepartmentSelect.svelte";
  import BaseButton from "$lib/components/common/BaseButton.svelte";
  import SelectField from "$lib/components/common/SelectField.svelte";
  import { createEventDispatcher } from "svelte";
  import { onMount } from 'svelte';
  
  const dispatch = createEventDispatcher();

  export let mode = "add"; // 'add' | 'edit'

  // 使用对象来管理表单数据
  export let formData = {
    knowledgeName: "",
    ragflowIds: [""],
    searchKeyword: "",
    apiKey: "",
    citationUrl: "",
    thirdPartyWhitelist: false,
    userWhitelist: false,
    departmentWhitelist: false,
    maxBlocks: 15,
    relevanceThreshold: 0.5,
    weightSort: 0.3,
    thirdPartyUsers: [""],
    userWhitelistUsers: [""],
    departmentWhitelistDepts: [],
  };

  const searchOptions = [
    { id: 1, name: "金融", description: "金融相关知识库搜索" },
    { id: 2, name: "银行", description: "银行业务知识库搜索" },
    { id: "investment", name: "投资", description: "投资理财知识库搜索" },
    { id: "insurance", name: "保险", description: "保险产品知识库搜索" },
    { id: "loan", name: "贷款", description: "贷款业务知识库搜索" },
  ];
  
  // 调试日志
  $: {
    console.log('KnowledgeForm: formData.searchKeyword 变化为:', formData.searchKeyword);
  }

  // 表单引用
  let formFields = {
    knowledgeName: null,
    ragflowIds: null,
    apiKey: null,
    userWhitelistUsers: null,
  };

  // 外部添加用户白名单行的方法
  function addUserWhitelistRow() {
    if (formFields.userWhitelistUsers) {
      formFields.userWhitelistUsers.addRow();
    }
  }

  // 验证表单
  function validateForm() {
    let isValid = true;

    // 必填校验
    if (formFields.knowledgeName && !formFields.knowledgeName.validate()) {
      isValid = false;
    }

    if (formFields.ragflowIds && !formFields.ragflowIds.validate()) {
      isValid = false;
    }

    // 自定义校验：验证ragflowIds格式
    if (formFields.ragflowIds) {


      // 校验不通过的数组
      const unvalidRows = ["asdasd", "1234567890"];


      const customValid = formFields.ragflowIds.validateCustom(
        (value, index) => {
          // 自定义验证逻辑：检查是否为有效的ID格式
          // return /^[a-zA-Z0-9_-]+$/.test(value.trim());
          // 自定义验证逻辑：是否在 unvalidRows 中
          return !unvalidRows.includes(value.trim());

        },
        "RAGFlow知识库ID格式不正确，请输入有效的字母、数字、下划线或横线组合"
      );
      
      if (!customValid) {
        isValid = false;
      }
    }

    if (formFields.apiKey && !formFields.apiKey.validate()) {
      isValid = false;
    }

    if (!isValid) {
      setTimeout(() => {
        const firstErrorField = document.querySelector(".field-error");
        if (firstErrorField) {
          firstErrorField.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }
      }, 100);
    }

    return isValid;
  }

  function handleSave() {
    if (!validateForm()) {
      return;
    }

    const submitData = {
      ...formData,
      ragflowIds: formData.ragflowIds.filter((id) => id.trim() !== ""),
    };

    dispatch("save", submitData);
  }

  function handleCancel() {
    // 清除表单错误
    Object.values(formFields).forEach((field) => {
      if (field && field.clearError) {
        field.clearError();
      }
    });

    dispatch("cancel");
  }

  // 添加部门数据相关状态
  let departmentTreeData = [];
  let loadingDepartments = false;
  let departmentError = null;
  
  // 获取部门数据
  async function fetchDepartmentData() {
    loadingDepartments = true;
    departmentError = null;
    
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟API返回的部门数据 - 使用不同的字段名
      departmentTreeData = [
        {
          deptId: 'headquarters',
          deptName: '总部',
          subDepts: [
            {
              deptId: 'finance',
              deptName: '财务部',
              subDepts: [
                { deptId: 'accounting', deptName: '会计科', subDepts: [] },
                { deptId: 'audit', deptName: '审计科', subDepts: [] }
              ]
            },
            {
              deptId: 'hr',
              deptName: '人力资源部',
              subDepts: [
                { deptId: 'recruitment', deptName: '招聘科', subDepts: [] },
                { deptId: 'training', deptName: '培训科', subDepts: [] }
              ]
            }
          ]
        }
      ];
    } catch (error) {
      console.error('获取部门数据失败:', error);
      departmentError = '获取部门数据失败，请重试';
      departmentTreeData = [];
    } finally {
      loadingDepartments = false;
    }
  }
  
  // 重新获取部门数据
  function retryFetchDepartments() {
    fetchDepartmentData();
  }
  
  onMount(() => {
    fetchDepartmentData();
  });
</script>

<div class="knowledge-item {mode}-form">
  <div class="config-content">
    <div class="left-panel">
      <div class="section">
        <h3>
          基本信息 <span class="edit-indicator"
            >{mode === "add" ? "新建模式" : "编辑模式"}</span
          >
        </h3>

        <FormField
          bind:this={formFields.knowledgeName}
          label="知识库名称"
          required={true}
          bind:value={formData.knowledgeName}
          placeholder="请输入知识库名称"
          maxLength={10}
        />

        <MultipleField
          bind:this={formFields.ragflowIds}
          label="RAGFlow知识库"
          required={true}
          bind:values={formData.ragflowIds}
          placeholder="请输入RAGFlow知识库ID"
          rowMaxLength={200}
        />

        <SelectField
          label="关联搜索词"
          bind:value={formData.searchKeyword}
          options={searchOptions}
          labelKey="name"
          valueKey="id"
          placeholder="请选择系统搜索词"
          clearable={true}
          on:change={(e) => {
            console.log('SelectField change event:', e.detail);
            // 可选：手动更新值
            // formData.searchKeyword = e.detail.value;
          }}
         />

        <FormField
          bind:this={formFields.apiKey}
          label="API Key 密钥"
          required={true}
          bind:value={formData.apiKey}
          placeholder="请输入API Key"
        />

        <FormField
          label="引文URL"
          bind:value={formData.citationUrl}
          placeholder="请输入知识引文所使用的URL地址"
        />
      </div>

      <div class="section">
        <h3>参数配置</h3>

        <div class="param-row">
          <NumberField
            label="单页最大块数"
            bind:value={formData.maxBlocks}
            min={1}
            max={100}
            step={1}
          />

          <NumberField
            label="相关性阈值"
            bind:value={formData.relevanceThreshold}
            min={0}
            max={1}
            step={0.01}
          />

          <NumberField
            label="权重分排序"
            bind:value={formData.weightSort}
            min={0}
            max={1}
            step={0.1}
          />
        </div>
      </div>
    </div>

    <div class="right-panel">
      <div class="section">
        <h3>权限配置</h3>

        <div class="permission-group">
          <SwitchField
            label="三方系统白名单"
            bind:checked={formData.thirdPartyWhitelist}
          />

          {#if formData.thirdPartyWhitelist}
            <div class="permission-content">
              <FormField
              bind:values={formData.thirdPartyUsers}
              placeholder="请输入三方系统的四或六位标识"
              on:change={(e) => (formData.thirdPartyUsers = e.detail)}
        
            />
            </div>
          {/if}
        </div>

        <div class="permission-group">
          <div class="permission-header">
            <SwitchField
              label="用户白名单"
              bind:checked={formData.userWhitelist}
            />
         
            {#if formData.userWhitelist}
              <BaseButton text size="small" on:click={addUserWhitelistRow}>
                <svg
                  slot="icon"
                  width="16"
                  height="16"
                  viewBox="0 0 16 16"
                  fill="currentColor"
                >
                  <path
                    d="M7.33398 7.83398V3.83398H8.66732V7.83398H12.6673V9.16732H8.66732V13.1673H7.33398V9.16732H3.33398V7.83398H7.33398Z"
                  />
                </svg>
              </BaseButton>
            {/if}
          </div>

          {#if formData.userWhitelist}
            <div class="permission-content">
              <MultipleField
                showHeader={false}
                bind:this={formFields.userWhitelistUsers}
                label="用户ID"
                type="number"
                min={1000}
                max={999999}
                step={1}
                bind:values={formData.userWhitelistUsers}
                placeholder="请输入用户ID (1000-999999)"
              />
            </div>
          {/if}
        </div>

        <div class="permission-group">
          <SwitchField
            label="部门白名单"
            bind:checked={formData.departmentWhitelist}
          />

          {#if formData.departmentWhitelist}
            <div class="permission-content">
              {#if loadingDepartments}
                <div class="loading-state">
                  <div class="loading-spinner"></div>
                  <span>正在加载部门数据...</span>
                </div>
              {:else if departmentError}
                <div class="error-state">
                  <span class="error-icon">⚠️</span>
                  <span class="error-text">{departmentError}</span>
                  <button class="retry-btn" on:click={retryFetchDepartments}>
                    重试
                  </button>
                </div>
              {:else}
                <DepartmentSelect
                  bind:selectedValues={formData.departmentWhitelistDepts}
                  treeData={departmentTreeData}
                  idKey="deptId"
                  nameKey="deptName"
                  childrenKey="subDepts"
                  maxVisibleTags={2}
                  placeholder="请选择部门"
                  on:change={(e) => (formData.departmentWhitelistDepts = e.detail.selectedValues)}
                />
              {/if}
            </div>
          {/if}
        </div>
      </div>
    </div>
  </div>

  <div class="actions">
    <BaseButton variant="text" on:click={handleCancel}>取消</BaseButton>
    <BaseButton variant="primary" on:click={handleSave}>保存</BaseButton>
  </div>
</div>

<style>
  .knowledge-item {
    background: #fff;
  }
  .knowledge-header {
    padding: 16px 20px;
    border-bottom: 1px solid #f0f0f0;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .edit-indicator {
    font-size: 12px;
    color: #1890ff;
    padding: 4px 8px;
    background: #e6f7ff;
    border-radius: 4px;
  }

  .config-content {
    display: grid;
    grid-template-columns: 1fr 1fr;
    border: 1px solid rgba(239, 239, 246, 1);
    background: #fff;
  }

  .left-panel {
    border-right: 1px solid rgba(239, 239, 246, 1);
    padding: 16px;
  }

  .right-panel {
    padding: 16px;

    background-color: rgba(0, 0, 0, 0.02);
  }

  .section {
    margin-bottom: 24px;
  }

  .section:last-child {
    margin-bottom: 0;
  }

  .section h3 {
    font-size: 14px;
    font-weight: 500;
    margin: 0 0 16px 0;
    color: rgba(36, 36, 36, 1);
    position: relative;
    padding-left: 8px;
  }

  .section h3::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-55%);
    width: 2px;
    height: 13px;
    background-color: rgba(69, 81, 229, 1);
  }

  .param-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
  }

  .actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 20px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  }
  .permission-group {
    margin-bottom: 20px;
    border: #e7e7eb 1px solid;
    background-color: #fff;
    padding: 12px;
    border-radius: 5px;
  }

  .permission-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
   }

  .permission-group:last-child {
    margin-bottom: 0;
  }

  .permission-content {
    margin-top: 12px;
    padding-left: 0;
  }

  .loading-state {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background: #f6f8fa;
    border: 1px solid #d0d7de;
    border-radius: 6px;
    color: #656d76;
    font-size: 14px;
  }
  
  .loading-spinner {
    width: 16px;
    height: 16px;
    border: 2px solid #f3f4f6;
    border-top: 2px solid #0969da;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .error-state {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px;
    background: #fff5f5;
    border: 1px solid #fed7d7;
    border-radius: 6px;
    color: #c53030;
    font-size: 14px;
  }
  
  .error-icon {
    font-size: 16px;
  }
  
  .error-text {
    flex: 1;
  }
  
  .retry-btn {
    padding: 4px 12px;
    border: 1px solid #c53030;
    border-radius: 4px;
    background: transparent;
    color: #c53030;
    cursor: pointer;
    font-size: 12px;
    transition: all 0.2s;
  }
  
  .retry-btn:hover {
    background: #c53030;
    color: white;
  }
  
  @media (max-width: 768px) {
    .config-content {
      grid-template-columns: 1fr;
      gap: 16px;
    }

    .param-row {
      grid-template-columns: 1fr;
      gap: 12px;
    }
  }
</style>
